package com.example.pan.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import androidx.appcompat.app.AppCompatDelegate
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.log10
import kotlin.math.pow


fun is64bit(): Boolean {
    return Arrays.binarySearch(Build.SUPPORTED_ABIS, "arm64-v8a") >= 0
}

fun formatDate(time: Long): String {
    val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINESE)
    return simpleDateFormat.format(Date(time * 1000))
}

fun formatBit(input: String): String {
    return formatBit(input.toLong())
}

fun formatBit(input: Long): String {
    if (input <= 0) {
        return "0B"
    }
    val units = arrayListOf("B", "KB", "MB", "GB", "TB")
    val digitGroups = (log10(input.toDouble()) / log10(1024.0)).toInt()
    return DecimalFormat("#,##0.##").format(input / 1024.0.pow(digitGroups.toDouble()))
        .toString() + units[digitGroups]

}

fun getAvailSpace(): String {
    return getAvailSpace(Environment.getDataDirectory().absolutePath)
}

private fun getAvailSpace(path: String): String {
    val statfs = StatFs(path)
    return formatBit(statfs.freeBytes) + "/" + formatBit(statfs.blockSizeLong * statfs.blockCountLong)
}

fun copy(input: String, context: Context) {
    val cmb = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cmb.setPrimaryClip(ClipData.newPlainText("Label", input))
}

fun setThemeMode(mode: String) {
    when (mode) {
        "light" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        "night" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
    }
}

